package com.fanqwz.kotlinmvvm.view

import android.arch.lifecycle.LifecycleOwner
import android.databinding.ViewDataBinding
import com.fanqwz.kotlinmvvm.databinding.AppDataBindingComponent
import com.fanqwz.kotlinmvvm.presenter.viewmodel.IModel
import com.fanqwz.kotlinmvvm.presenter.viewmodel.IViewModel
import com.fanqwz.kotlinmvvm.ui.compositor.ViewCompositor
import javax.inject.Inject

/**
 * Created by fanqwz on 2018/3/6.
 */

interface IView {
    val viewCompositor: ViewCompositor
    fun buildViewHierarchy(viewCompositorParent: ViewCompositor)
    fun <T : IModel> doBind(viewmodel: IViewModel<T>)
    fun start()
    fun stop()
    fun destroy()
}

class MVVM<V : IView, M : IModel, VM : IViewModel<M>> @Inject constructor() {
    @Inject
    lateinit var model: M
    @Inject
    lateinit var viewmodel: VM
    @Inject
    lateinit var view: V

    fun init() {
    }

    fun start() {
        view.doBind(viewmodel)
    }

    fun stop() {

    }

    fun destroy() {

    }
}


abstract class BaseView<V : ViewDataBinding> : IView {
    lateinit var binding:V
    @Inject
    lateinit var lifecycleOwner:LifecycleOwner
    @Inject
    lateinit var databindingComponent: AppDataBindingComponent

    override fun <T : IModel> doBind(viewmodel: IViewModel<T>) {
        binding.setLifecycleOwner(lifecycleOwner)
        onBind(viewmodel)
    }

    abstract fun <T : IModel> onBind(viewmodel: IViewModel<T>)
    open fun onStart() {}
    open fun onStop() {}
    open fun onDestroy() {}
    // call by BaseActivity::buildViewCompositor(),build viewCompositor tree
    override fun buildViewHierarchy(viewCompositorParent: ViewCompositor) {
        viewCompositorParent.addChild(viewCompositor)
    }

    final override fun start() {
        onStart()
    }

    final override fun stop() {
        onStop()
    }

    final override fun destroy() {
        onDestroy()
    }
}